import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:animated_tree_view/animated_tree_view.dart' as treeview;
import 'package:yuellyfactory/util/MathUtil.dart';
import '../../components/NoScrollbarBehavior.dart';
import '../../util/BaseRequest.dart';
import '../../util/ColorUtil.dart';
import '../../util/ViewUtil.dart';
import '../../util/XNumberTextInputFormatter.dart';
import '../dto/PricePart.dart';

class PriceVC extends StatefulWidget {
  const PriceVC({super.key});

  @override
  State<PriceVC> createState() => _PriceVCState();
}

class _PriceVCState extends State<PriceVC> {

  List allDatas=[];
  treeview.TreeViewController? _controller;
  var sampleTree = treeview.TreeNode.root();

  PricePart selectPricePart=PricePart();
  Map hasSelect={};

  List<String> hasSelectIds=[];
  double totalPrice=0.0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getAllData();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child:  ClipRRect(
        child: ShadResizablePanelGroup(
          children: [
            ShadResizablePanel(

              defaultSize: .7,
              minSize: .4,
              maxSize: .7,
              child: ShadResizablePanelGroup(
                axis: Axis.horizontal,
                children: [
                  ShadResizablePanel(
                    defaultSize: .6,
                    minSize: .4,
                    maxSize: .7,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Expanded(
                          child: Card( color: Colors.white,
                            child:
                            ScrollConfiguration(
                              behavior: NoScrollbarBehavior(),
                              child: SingleChildScrollView(
                                child:
                                Padding(
                                  padding: const EdgeInsets.all(5.0),
                                  child:
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      SizedBox(height: ViewUtil.screenWidth(10),),
                                      Row(
                                        children: [
                                          Text('已选配置',style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),),
                                          Expanded(child: Container()),
                                          Text(' ￥:${MathUtil.formatDouble(totalPrice, 2)}',style: TextStyle(fontSize: ViewUtil.fontSize(22)),),

                                        ],
                                      ),

                                      SizedBox(height: ViewUtil.screenWidth(10),width: double.infinity,),
                                      Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: getAllSelectData(),
                                      )
                                    ],
                                  )


                                  ,
                                ),),
                            ),

                          ),
                        ),
                      ],
                    ),

                  ),
                  ShadResizablePanel(
                    defaultSize: .4,
                    minSize: .3,
                    maxSize: .6,
                    child:
                    Card(
                        color: Colors.white,
                        child:Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(height: ViewUtil.screenHeight(10),),

                            // SizedBox(height: ViewUtil.screenHeight(10),),
                            Expanded(child:
                            treeview.TreeView.simple(
                                showRootNode: false,
                                focusToNewNode: false,
                                expansionIndicatorBuilder: (context, node) {
                                  return treeview.ChevronIndicator.rightDown(
                                      tree: node,
                                      alignment: Alignment.centerRight,
                                      //color: Colors.grey[700],
                                      color:ColorUtil.colorBlue
                                  );
                                },
                                indentation: const treeview.Indentation(
                                    style: treeview.IndentStyle.roundJoint),
                                onItemTap: (item) {
                                  print("Item tapped: ${item.key}");
                                  selectPricePart=item.data;
                                  setState(() {

                                  });
                                },
                                onTreeReady: (controller) {
                                  _controller = controller;
                                },
                                builder: (context, node) =>  Container(
                                  decoration: BoxDecoration(
                                    color: selectPricePart.id==node.key ? Colors.blue.withOpacity(0.1) : null,
                                    borderRadius: BorderRadius.circular(4),
                                  ),
                                  child: ListTile(
                                    title: Text("${node.data.name}",style: TextStyle(fontSize: ViewUtil.fontSize(22)),),
                                    trailing:  !hasSelectIds.contains(node.data.id)&&node.data.type=='type'?

                                    const Icon(Icons.circle,color: Colors.red,size: 12,)
                                        :null,

                                  ),
                                ),
                                tree: sampleTree),)

                          ],
                        )

                    ),
                  ),
                ],
              ),
            ),


            ShadResizablePanel(
              defaultSize: .3,
              child:
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    child: Card( color: Colors.white,
                      child:
                      ScrollConfiguration(
                        behavior: NoScrollbarBehavior(),
                        child: SingleChildScrollView(
                          child:
                          Padding(
                            padding: const EdgeInsets.all(5.0),
                            child:
                            Column(
                              children: [
                                SizedBox(height: ViewUtil.screenWidth(10),),
                                Row(
                                  children: [
                                    SizedBox(width: ViewUtil.screenWidth(10),),
                                    Expanded(child: Text(selectPricePart.name,
                                      style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold)
                                      ,),),

                                  ],
                                ),
                                if(selectPricePart.type=='serial')
                                  allPartWidgets()
                              ],
                            )


                            ,
                          ),),
                      ),

                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),


    );
  }


  void updateRedPoint(){
    List<String> selectIds=[];
    for(PricePart type in allDatas){
      for(PricePart brand in type.materialList){
        for(PricePart serial in brand.materialList){
          for(PricePart part in serial.materialList){
            if(part.select){
              selectIds.add(type.id);
              selectIds.add(brand.id);
              selectIds.add(serial.id);
              selectIds.add(part.id);
            }
          }
        }

      }
    }
    hasSelectIds=selectIds;

    setState(() {

    });
  }
  void updatePreConfig(Map selects){
    for(PricePart type in allDatas) {
      for (PricePart brand in type.materialList) {
        for (PricePart serial in brand.materialList) {
          for (PricePart part in serial.materialList) {
                if(selects.containsKey(part.id)){
                  part.select=true;
                  part.count=selects[part.id];
                }
          }
        }
      }
    }
    setState(() {

    });
  }

  Widget allPartWidgets(){

    List<Widget> views=[];
    for(PricePart part in selectPricePart.materialList){
      views.add(SizedBox(height: ViewUtil.screenHeight(10),));
      views.add(Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          FlutterSwitch(value: part.select,
              width: 40.0,
              height: 25.0,
              onToggle: (value){
                part.select=value;
                if(value){
                  if(part.config.isNotEmpty){
                    List list=jsonDecode(part.config);
                    Map selects={};
                    for(var item in list){
                      var id=item["id"];
                      var count=item["count"];
                      selects[id]=count;
                    }

                    updatePreConfig(selects);

                  }
                }
                updateRedPoint();
              }),
          SizedBox(width: ViewUtil.screenWidth(10),),
          Text(part.name),
          Expanded(child: Container()),
          Visibility(

              visible: part.select,
              child: SizedBox(width: 100,
                child: ShadInput(
                  textAlign: TextAlign.end,
                  initialValue: MathUtil.formatDouble(part.count, 2),
                  keyboardType: TextInputType.numberWithOptions(decimal: true),
                  inputFormatters: [
                    FilteringTextInputFormatter.allow(RegExp("[0-9.]")),
                    XNumberTextInputFormatter(
                        maxIntegerLength: null,
                        maxDecimalLength: 2,
                        isAllowDecimal: true),
                  ],
                  prefix: const Text('数量'),
                  placeholder: const Text('请输入数量'),
                  onChanged: (value){
                    part.count=double.parse(value);
                  },
                ),
              )),
        ],

      ));

      views.add(ViewUtil.lineView());
    }
    return Column(
      children: views,
    );
  }


  getAllSelectData(){
    List<Widget> widgets=[];
    double price=0;
    for(PricePart type in allDatas){
      bool hasAddType=false;
      for(PricePart brand in type.materialList){
        for(PricePart serial in brand.materialList){
          for(PricePart part in serial.materialList){
            if(part.select){
              if(!hasAddType){
                widgets.add(Text(type.name,style: TextStyle(fontSize: ViewUtil.fontSize(28),fontWeight: FontWeight.bold),),);
              }
              hasAddType=true;
              price=price+(part.count*part.price);
              widgets.add(Row(
                children: [
                  const SizedBox(width: 10,),
                  Text(part.name,style: TextStyle(fontSize: ViewUtil.fontSize(22)),),
                  Expanded(child: Container()),
                  Text('数量:${MathUtil.formatDouble(part.count, 2)} ￥:${MathUtil.formatDouble(part.price, 2)}',style: TextStyle(fontSize: ViewUtil.fontSize(22)),),

                ],
              ));
            }

          }
        }

      }
    }
    totalPrice=price;
    return widgets;
  }


  void getAllData(){
    BaseRequest.postHttp("price/baselist",parameters: {}, canTip: false , context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        dynamic datas=data["data"];
        List allParts=[];
        for(var i=0;i<datas.length;i++){
          var item=datas[i];
          var part=PricePart.fromJson(item);
          allParts.add(part);
        }
        allDatas=allParts;
        initTreeDatas(allParts);
      }


    }, onError: (error){

    });
  }


  void initTreeDatas(List allParts){
    var trees=treeview.TreeNode.root();
    for(PricePart part in allParts){
      if(selectPricePart.name.isEmpty){
        selectPricePart=part;
      }
      part.path=part.id;
      treeview.TreeNode node= treeview.TreeNode(key: part.id,data:part);
      for(PricePart brand in part.materialList){

        brand.path="${part.id}.${brand.id}";
        treeview.TreeNode brandNode=treeview.TreeNode(key: brand.id,data: brand);

        for(PricePart serial in brand.materialList){

          serial.path="${part.id}.${brand.id}.${serial.id}";
          treeview.TreeNode serialNode=treeview.TreeNode(key: serial.id,data: serial);

          for(PricePart part in serial.materialList){
            if(hasSelect.containsKey(part.id)){
              var count=hasSelect[part.id];
              part.select=true;
              part.count=double.parse(count.toString());
            }else{
              part.select=false;
              part.count=1;
            }
          }
          brandNode.add(serialNode);
        }
        node.add(brandNode);
      }
      trees.add(node);

    }
    sampleTree=trees;
    updateRedPoint();



  }
}
